﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using Telerik.Web.UI;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.IBLL;
using KPIS.GERP.GHRMS.MODEL;

namespace KPIS.GERP.GHRMS.APP.App_UI.Forms
{
    public partial class PS_AbsenceInforms : System.Web.UI.Page
    {
        private SsMng ssMng = new SsMng();
        private CommandControlBLL cmdFac = new CommandControlBLL();
        private IAbsenceBLL abBLL = new AbsenceBLL();
        private IAbsenceTypeBLL abtypeBLL = new AbsenceTypeBLL();
        private IEmployeeBLL empBLL = new EmployeeBLL();
        private IEmployeeTypeBLL etBLL = new EmployeeTypeBLL();
        private IPositionBLL posBLL = new PositionBLL();
        private IClassBLL classBLL = new ClassBLL();
        private IJobSiteBLL jsBLL = new JobSiteBLL();
        private UpperComboBLL approverBLL = new UpperComboBLL();

        private const int ItemsPerRequest = 10;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                CalendarDateStart.Attributes.Add("onload", "setCalendarDateStartTable();return false;");
                CalendarDateEnd.Attributes.Add("onload", "setCalendarDateEndTable();return false;");
                CalendarDateApproved.Attributes.Add("onload", "setCalendarDateApprovedTable();return false;");

                FillDataToEmpType();
                FillDataToJobSite();
                ListAbsenceType();
                cmbWorkingJobSite.SelectedValue = GetWorkingJobSite();
                LoadDataGrid();
            }

            txtCountDate.Attributes.Add("onkeypress", "return isNumberKeyDot(event)");
        }
        private static string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }
        private void LoadDataGrid()
        {
            DataSet ds = abBLL.LoadAbsences((int?)null, (int?)null);

            Grid.DataSource = ds;
            Grid.DataBind();

            cmdFac.GridCommand(panelList, panelGrid, panelCommand);                
        }
        protected void Grid_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "DataDelete")
            {
                int Sequence = Convert.ToInt32((e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["absence_seq"]);

                abBLL.Delete(Sequence, ssMng.EmpSeqI);
            }
            LoadDataGrid();
        }
        public void GetKeyValue(string Sequence)
        {
            DataTable dt = null;

            if (Sequence.Length > 0)
            {
                DataSet ds = abBLL.LoadAbsences(Convert.ToInt32(Sequence), (int?)null); //empBLL.LoadEmployees(Convert.ToInt32(Sequence), "", true, "");
                dt = ds.Tables[0].Copy();
                if (dt.Rows.Count > 0)
                {
                    cmbStatus.SelectedValue = dt.Rows[0]["APPROVED_STATUS"].ToString();//abInfo.Status;
                    cmbEmployee.Items.Add(new RadComboBoxItem(dt.Rows[0]["FULL_NAME"].ToString(), dt.Rows[0]["EMP_SEQ"].ToString()));
                    cmbEmployee.SelectedValue = dt.Rows[0]["EMP_SEQ"].ToString();//
                    cmbAbsenceType.SelectedValue = dt.Rows[0]["ABSENCE_TYPE_SEQ"].ToString();//

                    txtDateStart.TextWithLiterals = dt.Rows[0]["START_DATE"].ToString();
                    rdoStartTime.SelectedValue = dt.Rows[0]["START_TIME"].ToString();
                    txtDateEnd.TextWithLiterals = dt.Rows[0]["END_DATE"].ToString();
                    rdoEndTime.SelectedValue = dt.Rows[0]["END_TIME"].ToString();
                    txtCountDate.Text = string.Format("{0:N1}", dt.Rows[0]["COUNT_DATE"]);
                    txtContactAddress.Text = dt.Rows[0]["CONTACT_ADDRESS"].ToString();
                    txtReason.Text = dt.Rows[0]["REMARKS"].ToString();
                    cmbApprover.Items.Add(new RadComboBoxItem(dt.Rows[0]["APPROVED_NAME"].ToString(), dt.Rows[0]["APPROVED_BY"].ToString()));
                    cmbApprover.SelectedValue = dt.Rows[0]["APPROVED_BY"].ToString();
                    //txtApprovedPosition.Text = dt.Rows[0]["APPROVED_POSITION"].ToString();
                    txtDateApproved.TextWithLiterals = dt.Rows[0]["APPROVED_DATE"].ToString();
                }
            }
            cmdFac.ViewCommand(panelList, panelGrid, panelCommand);
        }
        public void FillDataToEmpType()
        {
            IList<EmployeeTypeInfo> InfoList = etBLL.ListEmployeeTypes(null);

            cmbEmpType.DataSource = InfoList;
            cmbEmpType.DataBind();
        }
        protected void FillDataToJobSite()
        {
            DataSet ds = jsBLL.LoadJobSites("", SystemInfo._JobsiteInternal, "", "");
            DataTable dt = new DataTable();
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
            }

            cmbWorkingJobSite.DataSource = dt;
            cmbWorkingJobSite.DataBind();
        }
        protected string GetWorkingJobSite()
        {
            string WorkingJobSite = "";

            DataSet ds = empBLL.LoadEmployees(ssMng.EmpSeqI, "", true, "");
            DataTable dt = null;
            if (ds != null)
            {
                dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                    WorkingJobSite = dt.Rows[0]["WORKING_JOB_SITE_SEQ"].ToString();
            }

            return WorkingJobSite;
        }
        protected void cmbEmployee_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            cmbEmployee.Items.Clear();

            Nullable<int> WorkingJobSite = string.IsNullOrEmpty(cmbWorkingJobSite.SelectedValue) ? (int?)null : Int32.Parse(cmbWorkingJobSite.SelectedValue);

            DataSet ds = empBLL.LoadEmployees((int?)null, "", (int?)null, WorkingJobSite, true, e.Text);
            DataTable dt = ds.Tables[0];

            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + ItemsPerRequest, dt.Rows.Count);
            e.EndOfItems = (endOffset == dt.Rows.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cmbEmployee.Items.Add(new RadComboBoxItem(dt.Rows[i]["FULL_NAME"].ToString(), dt.Rows[i]["EMP_SEQ"].ToString()));

                TableRow tr = new TableRow();

                TableCell tdPosName = new TableCell();
                Label lblPosName = new Label();
                lblPosName.Text = dt.Rows[i]["FULL_NAME"].ToString();
                tdPosName.Width = Unit.Pixel(150);
                tdPosName.Controls.Add(lblPosName);
                tr.Cells.Add(tdPosName);

                TableCell tdClassSpecName = new TableCell();
                Label lblClassSpecName = new Label();
                lblClassSpecName.Text = dt.Rows[i]["POS_NAME"].ToString();
                tdClassSpecName.Width = Unit.Pixel(100);
                tdClassSpecName.Controls.Add(lblClassSpecName);
                tr.Cells.Add(tdClassSpecName);

                TableCell tdJobName = new TableCell();
                Label lblJobName = new Label();
                lblJobName.Text = dt.Rows[i]["CLASS_NAME"].ToString();
                tdJobName.Width = Unit.Pixel(100);
                tdJobName.Controls.Add(lblJobName);
                tr.Cells.Add(tdJobName);

                ((Table)cmbEmployee.Items[j].FindControl("tableEmployee")).Controls.Add(tr);
                j++;
            }
            e.Message = GetStatusMessage(endOffset, dt.Rows.Count);
        }
        protected void cmbApprover_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            cmbApprover.Items.Clear();

            DataTable dt = approverBLL.ListUpperPosition(Int32.Parse(cmbEmployee.SelectedValue), 1, 0);

            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + ItemsPerRequest, dt.Rows.Count);
            e.EndOfItems = (endOffset == dt.Rows.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cmbApprover.Items.Add(new RadComboBoxItem(dt.Rows[i]["FULL_NAME"].ToString(), dt.Rows[i]["EMP_SEQ"].ToString()));

                TableRow tr = new TableRow();

                TableCell tdPosName = new TableCell();
                Label lblPosName = new Label();
                lblPosName.Text = dt.Rows[i]["FULL_NAME"].ToString();
                tdPosName.Width = Unit.Pixel(150);
                tdPosName.Controls.Add(lblPosName);
                tr.Cells.Add(tdPosName);

                TableCell tdClassSpecName = new TableCell();
                Label lblClassSpecName = new Label();
                lblClassSpecName.Text = dt.Rows[i]["EXEC_POS_NAME"].ToString();
                tdClassSpecName.Width = Unit.Pixel(100);
                tdClassSpecName.Controls.Add(lblClassSpecName);
                tr.Cells.Add(tdClassSpecName);

                TableCell tdJobName = new TableCell();
                Label lblJobName = new Label();
                lblJobName.Text = dt.Rows[i]["CLASS_NAME"].ToString();
                tdJobName.Width = Unit.Pixel(100);
                tdJobName.Controls.Add(lblJobName);
                tr.Cells.Add(tdJobName);

                ((Table)cmbApprover.Items[j].FindControl("tableApprover")).Controls.Add(tr);
                j++;
            }
            e.Message = GetStatusMessage(endOffset, dt.Rows.Count);
        }
        private void ListAbsenceType()
        {
            IList<AbsenceTypeInfo> infoList = abtypeBLL.ListAbsenceTypes();

            cmbAbsenceType.DataSource = infoList;
            cmbAbsenceType.DataBind();
        }
        protected void RadManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            if (e.Argument == "CloseWindow")
            {
            }
            else
            {
                GetKeyValue(e.Argument);
            }
        }
        protected void ShowGrid_Click(object sender, EventArgs e)
        {
            LoadDataGrid();
        }
        protected void AddNew_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList, panelGrid, panelCommand);

        }
        protected void Edit_Click(object sender, EventArgs e)
        {
            cmdFac.EditCommand(panelList, panelGrid, panelCommand);
            //if (RadAjaxPanel2.Visible)
            //{
            //    VisibleTextBox(txtFromTransfer, lblFromTransfer);
            //    VisibleTextBox(txtTranRefNo, lblTranRefNo);
            //}
            //if (RadAjaxPanel3.Visible)
            //{
            //    VisibleComboBox(lblDN, cmbDN);
            //}
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            if (panelGrid.Visible)
            {
                //int Sequence = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["icm_receive_seq"]);
                //bll.Delete(Sequence, ssMng.EmpSeq);
            }
            else
            {
                abBLL.Delete(Int32.Parse(hdSequence.Value), ssMng.EmpSeqI);
            }

            if (string.IsNullOrEmpty(hdSequence.Value))
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            LoadDataGrid();
        }

        protected void AddNewSave_Click(object sender, EventArgs e)
        {
            abBLL.Insert(cmbAbsenceType.SelectedValue
                , cmbEmployee.SelectedValue
                , DateTime.Parse(txtDateStart.TextWithLiterals)
                , rdoStartTime.SelectedValue
                , DateTime.Parse(txtDateEnd.TextWithLiterals)
                , rdoEndTime.SelectedValue
                , decimal.Parse(txtCountDate.Text)
                , txtContactAddress.Text.Trim()
                , cmbStatus.SelectedValue
                , cmbApprover.SelectedValue
                , "" //txtApprovedPosition.Text.Trim()
                , txtDateApproved.Text.Length > 0 ? DateTime.Parse(txtDateApproved.TextWithLiterals) : (DateTime?)null
                , txtReason.Text.Trim()
                , ssMng.EmpSeqI);
            LoadDataGrid();
        }

        protected void EditSave_Click(object sender, EventArgs e)
        {
            abBLL.Update(Int32.Parse(hdSequence.Value)
                , cmbAbsenceType.SelectedValue
                , cmbEmployee.SelectedValue
                , DateTime.Parse(txtDateStart.TextWithLiterals)
                , rdoStartTime.SelectedValue
                , DateTime.Parse(txtDateEnd.TextWithLiterals)
                , rdoEndTime.SelectedValue
                , decimal.Parse(txtCountDate.Text)
                , txtContactAddress.Text.Trim()
                , cmbStatus.SelectedValue
                , cmbApprover.SelectedValue
                , "" //txtApprovedPosition.Text.Trim()
                , txtDateApproved.Text.Length > 0 ? DateTime.Parse(txtDateApproved.TextWithLiterals) : (DateTime?)null
                , txtReason.Text.Trim()
                , ssMng.EmpSeqI);
        }

        protected void Cancel_Click(object sender, EventArgs e)
        {
            cmdFac.CancelCommand(panelList, panelGrid, panelCommand);
        }

        protected void cmbEmpType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadDataGrid();
        }

        protected void cmbWorkingJobSite_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadDataGrid();
        }

    }
}
